package basic;


import java.util.Collections;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.*;
/**
 * Java 8 Optional类深度解析
 */
public class OptionalDemo {

    //这是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true，调用get()方法会返回该对象。
    public static void main(String[] args) {
        String str = "hello,world!";
        String nullStr = null;
        Optional<String> optionalS = Optional.of(str);

        Optional<String> optionalS1 = Optional.ofNullable(nullStr);

        try {
            Optional<String> optionalS2 = Optional.of(nullStr);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        System.out.println(optionalS.isPresent());
        System.out.println(optionalS.get());

        System.out.println(optionalS1.isPresent());
        try {
            System.out.println(optionalS1.get());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


        optionalS.ifPresent(v ->{
            System.out.println("optionalS:" + v);
        });

        optionalS1.ifPresent(v ->{
            System.out.println("optionalS1:" + v);
        });


        System.out.println(optionalS1.orElse("other"));
        System.out.println(optionalS1.orElseGet(() -> "get other"));
        try {
            System.out.println(optionalS1.orElseThrow(Exception::new));
        } catch (Exception e) {
            System.out.println("orElseThrow");
        }

        Optional<String> optional =  optionalS.map(v -> "map:" + v);
        System.out.println(optional.get());

        Optional<String> optional1 = optional.flatMap(v -> Optional.of("flatMap"));
        System.out.println(optional1.get());

        Optional<String> optional2 = optional1.filter(v -> v.contains("a"));
        Optional<String> optional3 = optional1.filter(v -> v.contains("c"));
        System.out.println(optional3.orElse("empty"));
        System.out.println(optional2.get());

    }
}
